#include "widget.h"
#include "ui_widget.h"
#include <QFileDialog>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    this->setWindowTitle("Same File Check");

    thread.start();
    md5.moveToThread(&thread);
    //qRegisterMetaType<QHash<QByteArray,QStringList>>("QHash<QByteArray,QStringList>");
    qRegisterMetaType<QHash<QByteArray,QStringList> >("QHash<QByteArray,QStringList>");
    connect(&md5,SIGNAL(gotDuplicate(QHash<QByteArray,QStringList>)),
            this,SLOT(ongotDuplicate(QHash<QByteArray,QStringList>)));
    connect(this,SIGNAL(checkDuplicate(QString)),
            &md5,SLOT(checkDuplicate(QString)));
    connect(&md5,SIGNAL(progress(int,int)),
            this,SLOT(onProgress(int,int)));
}

Widget::~Widget()
{
    thread.exit();
    thread.wait(4*1000);
    delete ui;
}

void Widget::ongotDuplicate(const QHash<QByteArray, QStringList> &duplicates)
{
    this->duplicates = duplicates;
    for(QHash<QByteArray,QStringList>::const_iterator ite = duplicates.begin();
        ite!=duplicates.end();++ite)
    {
        if(ite.value().count()>1)
        {
            ui->listWidget_md5->addItem(ite.key().toHex());
        }
    }
}

void Widget::on_btn_open_clicked()
{
    ui->listWidget_md5->clear();
    QString path = QFileDialog::getExistingDirectory(this,"select a dir",".");
    ui->progressBar->setValue(0);
    ui->lineE_path->setText(path);

    emit checkDuplicate(path);
}

void Widget::onProgress(int current, int total)
{
    ui->progressBar->setMaximum(total);
    ui->progressBar->setValue(current);
}


void Widget::on_listWidget_md5_currentTextChanged(const QString &currentText)
{
    ui->listWidget_files->clear();
    for(QHash<QByteArray,QStringList>::iterator ite = duplicates.begin();
        ite!=duplicates.end();ite++)
    {
        if(ite.value().count()>1 && QString(ite.key().toHex()) == currentText)
            ui->listWidget_files->addItems(ite.value());
            //qDebug() << ite.value();
    }
}
